<script setup>
import { ref, onMounted, getCurrentInstance, watch, computed } from 'vue'
import api from '@/api/index.js'

const emits = defineEmits(['update:modelValue'])

const props = defineProps({
  modelValue: {
    type: [Number, String],
    default: ''
  },
  params: {
    type: Object,
    default: () => ({
      size: 9999,
      productType: ''
    })
  },
  getRows: {
    type: Object,
    default: () => {}
  }
})

const attrs = ref({})

onMounted(() => {
  const { ctx } = getCurrentInstance()
  const attrs = ref({})
  attrs.value = ctx.$attrs
})

const sltVal = ref('')

const change = (e) => {
  sltVal.value = e?.[0] ? [e[e.length - 1]] : []
  emits('update:modelValue', sltVal.value?.[0] || '')
}

const options = ref([])

const objBind = computed(() => {
  return {
    mode: 'tags',
    filterOption: false,
    options: options.value,
    ...attrs.value
  }
})

const testList = ref([])

const getOptions = async (para) => {
  let paraList = {
    ...para,
    size: 9999
  }
  const {
    data: { records }
  } = await api.getKcList(paraList)
  options.value = records.map((item) => ({
    label: item.productName,
    value: item.id
  }))
  testList.value = options.value
}
watch(
  () => props.modelValue,
  (val) => {
    sltVal.value = val ? [val] : []
    props.getRows && props.getRows(testList.value, val)
  },
  { immediate: true }
)

watch(
  () => props.params,
  (p) => {
    getOptions(p)
  },
  { deep: true, immediate: true }
)
</script>

<template>
  <a-select v-bind="objBind" v-model:value="sltVal" @change="change" />
</template>